package com.augurit.wf.jbpmex.cmd;


import java.util.List;

import org.jbpm.api.ExecutionService;
import org.jbpm.api.HistoryService;
import org.jbpm.api.cmd.Environment;
import org.jbpm.api.history.HistoryTask;
import org.jbpm.api.task.Task;
import org.jbpm.pvm.internal.cmd.AbstractCommand;
import org.jbpm.pvm.internal.history.model.HistoryTaskImpl;
import org.jbpm.pvm.internal.model.ActivityImpl;
import org.jbpm.pvm.internal.model.ExecutionImpl;
import org.jbpm.pvm.internal.session.DbSession;
import org.jbpm.pvm.internal.util.Clock;

/**
 * 流程监控时,系统管理员完成多工作项
 * @author Administrator
 *
 */
public class CompleteMultTaskByAdminCmd extends AbstractCommand<Void>{
	private static final long serialVersionUID = 1L;
	  
	protected String executionId;
	
	public CompleteMultTaskByAdminCmd(String executionId){
		this.executionId = executionId;
	}
	
	public Void execute(Environment environment) throws Exception {
		ExecutionService executionService = environment.get(ExecutionService.class);
		ExecutionImpl execution = (ExecutionImpl)executionService.findExecutionById(executionId);
		DbSession dbSession = environment.get(DbSession.class);
		ActivityImpl activity = execution.getActivity();
		String outcome = activity.getOutgoingTransitions().get(0).getName();
		
		//TIDO 修改历史记录数据
		updateHistoryTask(environment,dbSession,execution.getActivityName(),outcome);
		
		//删除所有的task
		deleteTasksByExecutionId(environment,dbSession);
		
		
		execution.take(outcome);
	    return null;
	}
	
	
	public void deleteTasksByExecutionId(Environment environment,DbSession dbSession){
		List<Task> list = dbSession.createTaskQuery().executionId(executionId).list();
		    
		//删除所有task
		if(list != null && list.size() > 0){
		for(Task task :list)
		   dbSession.delete(task);
		}
	}
	
	public void updateHistoryTask(Environment environment,DbSession dbSession,String activityName,String outcome){
		HistoryService historyService  = environment.get(HistoryService.class);
		List<HistoryTask> list = historyService.createHistoryTaskQuery().executionId(executionId).list();
		    
		//修改所有HistoryTask
		if(list != null && list.size() > 0){
			for(HistoryTask hisTask :list){
				if(hisTask.getActivityName().equals(activityName)){
					HistoryTaskImpl hisTaskImpl = (HistoryTaskImpl)hisTask;
					hisTaskImpl.setEndTime(Clock.getTime());
					hisTaskImpl.setState(HistoryTask.STATE_COMPLETED);
					hisTaskImpl.setOutcome(outcome);
					dbSession.update(hisTaskImpl);
				}
			}
		}
	}
	
}
